package xyz.thoughtset.viewer.modules.api.controller;


import cn.idev.excel.ExcelWriter;
import cn.idev.excel.FastExcel;
import cn.idev.excel.write.metadata.WriteSheet;
import cn.idev.excel.write.metadata.fill.FillConfig;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import xyz.thoughtset.viewer.common.api.controller.BaseController;
import xyz.thoughtset.viewer.common.core.constants.FolderNameConstant;
import xyz.thoughtset.viewer.modules.api.constants.ApiParamTypeConstant;
import xyz.thoughtset.viewer.modules.api.entity.ApiInfo;
import xyz.thoughtset.viewer.modules.api.entity.ApiParam;
import xyz.thoughtset.viewer.modules.api.service.ApiInfoService;
import xyz.thoughtset.viewer.modules.excel.entity.ExportDataInfo;
import xyz.thoughtset.viewer.modules.excel.service.ExportDataInfoService;
import xyz.thoughtset.viewer.modules.step.executor.SimpleBlockExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("/eq/")
public class EasyQueryController extends BaseApiController {


    @GetMapping(value = "{subject}")
    @ResponseBody
    public Object query(@RequestParam(required = false) LinkedHashMap<String, Object> searchMap
            , @PathVariable("subject") String subject) {
        ApiInfo apiInfo = apiInfoService.getById(subject);
        return doQuery(searchMap, apiInfo);
    }


    @GetMapping(value = "e/{subject}")
    @ResponseBody
    public void excel(@RequestParam(required = false) LinkedHashMap<String, Object> searchMap
            , @PathVariable("subject") String subject, HttpServletResponse response) {
        ExportDataInfo exportDataInfo = exportDataService.getById(subject);
        if (exportDataInfo == null) {
            throw new NullPointerException("exportData not found");
        }
        Map<String, Object> data = (Map<String, Object>) query(searchMap, exportDataInfo.getBodyId());
        String fileName = exportDataInfo.getFileName();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
//        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        try (
                InputStream templateStream = new FileInputStream(
                        FolderNameConstant.folderWithSep(FolderNameConstant.TEMPLATE,exportDataInfo.getTemplateId()));
                ExcelWriter writer =
                         FastExcel.write(response.getOutputStream())
                                 .withTemplate(templateStream).build()) {
            WriteSheet writeSheet = FastExcel.writerSheet().build();

            for (Map.Entry<String, Object> entry : data.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                writer.fill(value, writeSheet);
            }
            writer.finish();
        }catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }


}
